<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		computed,
		reactive
	} from 'vue'
	import Drawer from '@/components/Drawer.vue'
	import ConsumableList from '@/components/ConsumableList.vue'
	import {
		ElCard,
		ElTable,
		ElTableColumn,
		ElMessage,
		ElTag
	} from 'element-plus'
	import {
		Search,
		Plus,
		Refresh,View
	} from '@element-plus/icons-vue'
	import {
		getLocationTree,
		getBorrowerPersonList,
		getBorrowerList,
		addBorrower,
		getBorrowerDept,
		getBorrowerDetail,
		getBorrowerMaterialDetail,
		getMaterialBorrowerList

	} from "@/api/AssetBorrow"
	import {
		getConsumablesStoreList,
	} from "@/api/ConsumablesStore.js"

	/***********耗材借用表单数据******** */
	// 分页配置
	const pagination = reactive({
		pageNum: 1,
		pageSize: 10,
		total: 0
	})


	// 仓库列表数据
	const StoreListData = ref([])

	// 新增耗材借用弹框状态
	const formVisible = ref(false)

	// 耗材借用表单实例对象
	const formRef = ref(null)

	// 耗材借用弹框标题
	const title = ref('')

	// 耗材借用表单数据
	const borrowForm = ref({
		userId: null,
		assignDate: new Date().toISOString().split('T')[0], // 借用日期，默认今天
		expectedReturn: new Date().toISOString().split('T')[0], // 预计归还日期，默认今天
		deptId: null,
		locationId: null,
		usagePurpose: "",
		assets: [],
		type: 1, //0资产、1耗材
	})

	// 资产所在部门列表数据
	const assetDept = ref([]);


	// 借用后资产位置树形数据
	const parentLocations = ref([])

	// 获取位置树形结构
	const getLocationTreeData = () => {
		getLocationTree().then(res => {
			if (res.code === 200) {
				parentLocations.value = res.data
			}
		})
	}


	// 提交资产借用表单
	const handleSubmit = () => {
		// 添加表单校验
		borrowForm.value.type = 1
		borrowForm.value.locationId = borrowForm.value.warehouseId
		//耗材校验
		if (borrowForm.value.assets.length <= 0) {
      return ElMessage.error('请选择需要出库的耗材！')
    }

		formRef.value.validate(async (valid) => {
			if (valid) {
				addBorrower(borrowForm.value).then(res => {
					if (res.code === 200) {
						ElMessage.success(`出库成功`);
						formVisible.value = false;
						// 调用子组件的取消选中方法
						assetsListRef.value?.clearSelection()
						resetForm();
						getBorrowAssetListData()
					}
				});
			}
		})
	}

	// 资源借出列表数据
	const borrowerList = ref([])

	// 获取借出列表
	const getBorrowAssetListData = () => {
		let data = {
			...pagination,
			userId: queryForm.value.userId,
			type: 1 //领用类型 0-资产 1-耗材
		}
		getMaterialBorrowerList(data).then(res => {
			if (res.code === 200) {
				/* let lists = []
				 res.data.list.forEach(item => {

				 })*/
				borrowerList.value = res.data.list
				pagination.total = res.data.total
			}
		})
	}



	// 是否为编辑状态
	const isEditMode = ref(false)


	// 重置表单
	const resetForm = () => {
		isEditMode.value = false;
		formRef.value?.resetFields();
		borrowForm.value = {
			userId: null,
			assignDate: new Date().toISOString().split('T')[0], // 借用日期，默认今天
			expectedReturn: new Date().toISOString().split('T')[0], // 预计归还日期，默认今天
			deptId: null,
			locationId: null,
			usagePurpose: "",
			assets: []
		}
	}


	//点击借出按钮
	const addBorrowData = () => {
		//重置表单 修改编辑状态
		resetForm()
		// 获取可借用资产
		// getAssetListData()
		//弹框显示
		formVisible.value = true
		//弹框标题
		title.value = '新增耗材领用'
	}


	// 借用人相关状态
	const borrowPersonLoading = ref(false)
	const borrowerPersonOptions = ref([])

	// 搜索借用人
	const searchBorrowerPerson = async (query) => {
		if (query) {
			borrowPersonLoading.value = true
			try {
				const res = await getBorrowerPersonList({
					username: query
				})
				if (res.code === 200) {
					borrowerPersonOptions.value = res.data
					//handleBorrowerChange(res.data.id)
				}
			} finally {
				borrowPersonLoading.value = false
			}
		} else {
			borrowerPersonOptions.value = []
		}
	}

	// 处理借用人选择变化 获取选中的人的详细信息
	const handleBorrowerChange = async (personId) => {
		console.log(personId, 7878)
		//借用人选择变化后 获取借用的username

		if (!personId) return;

		// 获取借用人详情
		const res = await getBorrowerDept(personId);
		if (res.code === 200) {
			// 自动填充部门信息
			assetDept.value = res.data.departments;
			// borrowForm.value.deptId = res.data.deptId;
		}
	}


	// 禁止选中当前日期之前的日期
	const disabledExpectedReturnDate = (time) => {
		return time.getTime() < new Date(borrowForm.value.assignDate).getTime()
	}

	// 定义子组件 ref
	const assetsListRef = ref(null)

	// 点击取消关闭弹框
	const handleCancel = () => {
		formVisible.value = false
		// 调用子组件的取消选中方法
		assetsListRef.value?.clearSelection()
	}

	// 获取子组件选择借用的资产
	const handleAssetSelect = (assetList) => {
		borrowForm.value.assets = assetList
		//console.log(assetList, 9999)
	}

	// 控制 Drawer 显示状态
	const drawerVisible = ref(false)

	// 点击编号时触发的方法
	const handleClickTag = (id) => {
		// 给Drawer传递数据 打开 Drawer
		// 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
		getBorrowerMaterialDetail({
			"id": id,
			type: 1
		}).then(res => {
			if (res.code === 200) {
				//console.log(res,"详情数据")
				nextTick(() => {
					showFormData.value.id = res.data.id
					showFormData.value.createTime = res.data.createTime
					showFormData.value.username = res.data.username
					showFormData.value.deptName = res.data.deptName
					showFormData.value.expectedReturn = res.data.expectedReturn
					showFormData.value.locationName = res.data.locationName
					showFormData.value.usagePurpose = res.data.usagePurpose
					showFormData.value.operatorName = res.data.operatorName
					tableData.value = res.data.materialBorrowVoList
					//console.log(formDataValues.value,7777)
				})
			}
		})
		drawerVisible.value = true
	}

	// 资产列表搜索框绑定的资产id
	const queryForm = ref({
		id: '',
		userId: ""
	})
	// 根据资产id查询借用列表
	const handleBorrowSearch = () => {
		/*if (!queryForm.value.id) {
		  //ElMessage.warning('请输入资产id');
		  return;
		}*/

		let data = {
			...pagination,
			userId: queryForm.value.userId,
			type: 1 //领用类型 0-资产 1-耗材
		}
		getMaterialBorrowerList(data).then(res => {
			if (res.code === 200) {
				borrowerList.value = res.data.list
			}
		})
	}

	// 重置资源借用列表数据
	const handleBorrowReset = () => {
		queryForm.value.userId = ''
		getBorrowAssetListData()
	}

	const showFormData = ref({
		id: '',
		createTime: "",
		username: '',
		deptName: '',
		expectedReturn: '',
		locationName: '',
		usagePurpose: '',
		operatorName: '',
		assets: []
	})

  const formDataValues = computed(() => [
    {
      label: '借用人部门:',
      value: showFormData.value.deptName
    },
    {
      label: '借用人:',
      value: showFormData.value.username
    },
    {
      label: '经办人:',
      value: showFormData.value.operatorName
    },
    {
      label: '出库仓库:',
      value: showFormData.value.locationName
    },
    {
			label: '出库时间:',
			value: showFormData.value.createTime
		},
		{
			label: '备注:',
			value: showFormData.value.usagePurpose
		}
	])

	// tableData
	const tableColumns = ref([{
			prop: 'code',
			label: '耗材编码'
		},
		{
			prop: 'name',
			label: '耗材名称'
		},
		{
			prop: 'categoryName',
			label: '耗材分类'
		},
		{
			prop: 'specification',
			label: '规格'
		},
		{
			prop: 'unit',
			label: '单位'
		},
		{
			prop: 'warehouseName',
			label: '出库仓库'
		},
		{
			prop: 'quantity',
			label: '当前库存'
		},
		{
			prop: 'materialNum',
			label: '出库数量'
		},
    // {
    // 	prop: 'materialDesc',
    // 	label: '出库备注'
    // },
	])

	const tableData = ref([])

	// 关闭 Drawer 的方法
	const closeDrawer = () => {
		drawerVisible.value = false
	}

	const rules = {
		userId: [{
			required: true,
			message: '请选领用用人',
			trigger: 'change'
		}],
		locationId: [{
			required: true,
			message: '请选择出库',
			trigger: 'change'
		}],
		warehouseId: [{
			required: true,
			message: '请选择出库',
			trigger: 'change'
		}],
		assignDate: [{
			required: true,
			message: '请选择出库日期',
			trigger: 'change'
		}],
		deptId: [{
			required: true,
			message: '请选择部门',
			trigger: 'change'
		}],
		usagePurpose: [{
			max: 200,
			message: '备注长度不能超过200个字符',
			trigger: 'blur'
		}]
	}

	/*********** 页面加载时获取数据 *********/
	onMounted(() => {
		//获取位置树数据
		getLocationTreeData()

		//获取借出列表数据
		getBorrowAssetListData()

		//获取仓库
		getConsumablesStoreList().then(res => {
			StoreListData.value = res.data
		})
	})

	//分页
	const handleSizeChange = (val) => {
		console.log(`${val} items per page`)
		pagination.pageSize = val
		getBorrowAssetListData()
	}
	const handleCurrentChange = (val) => {
		console.log(`current page: ${val}`)
		pagination.pageNum = val
		getBorrowAssetListData()
	}
</script>

<template>
	<div class="page-container">
		<!-- 新增资产借出按钮与按资产名称搜索借用资源列表 -->

		<!-- 搜索框 -->
		<el-form :inline="true" :model="queryForm" style="margin-top: 10px;">
			<el-form-item>
				<el-space>
					<el-select v-model="queryForm.userId" filterable remote reserve-keyword placeholder="请输入领用人姓名"
						:remote-method="searchBorrowerPerson" :loading="borrowPersonLoading"
						@change="handleBorrowerChange" clearable style="width: 230px">
						<el-option v-for="item in borrowerPersonOptions" :key="item.id" :label="item.username"
							:value="item.id">
						</el-option>
						<!-- 使用图标组件 -->
						<template #prefix>
							<el-icon>
								<Search />
							</el-icon>
						</template>
					</el-select>
          <el-button type="primary" :icon="Search"
						@click="handleBorrowSearch">查询</el-button>
					<el-button type="primary" plain :icon="Refresh" @click="handleBorrowReset">重置</el-button>
					<el-button plain type="primary" :icon="Plus" @click="addBorrowData">
						新增
					</el-button>
				</el-space>
			</el-form-item>
		</el-form>


		<!- 新增耗材领用弹框表单 ->
		<el-dialog v-model="formVisible" @close="handleCancel" close-on-click-modal="false" :title="title" width="75%">
			<el-form :model="borrowForm" :rules="rules" ref="formRef" label-width="120px" inline>
				<el-form-item label="领用人" prop="userId">
					<el-select v-model="borrowForm.userId" filterable remote reserve-keyword placeholder="请输入领用人姓名"
						:remote-method="searchBorrowerPerson" :loading="borrowPersonLoading"
						@change="handleBorrowerChange" style="width: 300px">
						<el-option v-for="item in borrowerPersonOptions" :key="item.id" :label="item.username"
							:value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="领用部门" prop="deptId" :rules="[{required:true,message:'请选择领用部门'}]">
					<el-tree-select v-model="borrowForm.deptId" placeholder="请选择领用部门" :data="assetDept" node-key="id"
						:props="{label:'deptName',children:'children'}" check-strictly :render-after-expand="false"
						style="width: 300px"></el-tree-select>
				</el-form-item>

				<el-form-item label="出库仓库" prop="warehouseId">
					<el-select v-model="borrowForm.warehouseId" placeholder="请选择出库仓库" style="width: 300px" clearable>
						<el-option v-for="st in StoreListData" :label="st.name" :value="st.id" :key="st.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="出库日期" prop="assignDate">
					<el-date-picker v-model="borrowForm.assignDate" type="date" placeholder="选择出库日期"
						style="width: 300px" value-format="YYYY-MM-DD" />
				</el-form-item>

				<el-form-item label="备注" class="full-width">
					<el-input v-model="borrowForm.usagePurpose" type="textarea" :rows="3" placeholder="请输入备注内容"
						maxlength="200" show-word-limit />
				</el-form-item>

				<!-- 资产列表 <ConsumableList :status="0" ref="assetsListRef" @assetSelect="handleAssetSelect"/> -->
				<ConsumableList :wid="borrowForm.warehouseId" @consumableSelect="handleAssetSelect" />

				<div class="dialog-footer">
					<el-button @click="handleCancel">取消</el-button>
					<el-button type="primary" @click="handleSubmit">确定</el-button>
				</div>
			</el-form>
		</el-dialog>

		<!-借用信息列表 ->
    <el-table :data="borrowerList" table-layout="auto" height="80%">
      <el-table-column prop="deptName" label="领用人部门" align="left"/>
      <el-table-column prop="username" label="领用人姓名" align="center"/>
      <el-table-column prop="operatorName" label="经办人" align="center"/>
      <el-table-column prop="locationName" label="仓库位置" align="center"/>
			<el-table-column prop="createTime" label="领用日期" align="center"  />
			<!-- <el-table-column prop="usagePurpose" label="备注" align="center" /> -->
			<el-table-column prop="id" label="操作" align="center"  width="150">
				<template #default="scope">
					<el-link type="primary" @click="handleClickTag(scope.row.id)" size="small">
						<el-icon><el-icon-edit /></el-icon>查看</el-link>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
			:total="pagination.total" layout="slot, prev, pager, next" style="margin-top: 20px"
			@size-change="handleSizeChange" @current-change="handleCurrentChange"><el-text
				key="1">总条数：{{ pagination.total }}</el-text></el-pagination>

		<!- 耗材出库详情抽屉 ->
		<Drawer v-model:visible="drawerVisible" :formData="showFormData" :title="'耗材出库详情'"
			:formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableData" @close="closeDrawer" />
	</div>
</template>

<style scoped lang='less'>
	.mb-4 {
		margin-bottom: 1rem;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	// 添加级联面板样式
	:deep(.cascader-popper) {
		.el-cascader-node:not(.is-leaf)>.el-cascader-node__label {
			color: #409EFF;

			&::after {
				content: '（可选）';
				font-size: 12px;
				color: #999;
			}
		}
	}

	.full-width {
		width: 100%;

		.el-textarea {
			width: 100%;
		}
	}

	.el-pagination {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}
</style>